package com.cykj.admin.aspect;

import cn.dev33.satoken.stp.StpUtil;
import com.cykj.admin.annotation.MyLog;
import com.cykj.admin.service.ILogService;
import com.cykj.common.entity.LogDO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @BelongsProject: smart_recruit_backend
 * @BelongsPackage: com.cykj.admin.aspect
 * @Author: 小小卢
 * @CreateTime: 2025-08-29 11:35
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    private ILogService logService;

    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("@annotation( com.cykj.admin.annotation.MyLog )")
    public void logPoinCut() {
    }

    //切面 配置通知
    @AfterReturning("logPoinCut()")
    public void saveLog(JoinPoint joinPoint) {
        //保存日志
        LogDO logDO = new LogDO();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();

        //获取操作
        MyLog myLog = method.getAnnotation(MyLog.class);
        if (myLog != null) {
            logDO.setOperation(myLog.value());//保存获取的操作
        }

        //设置方法名
        logDO.setMethod(method.getName());

        //设置操作时间
        Date now = new Date();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(
                now.toInstant(),
                ZoneId.systemDefault()
        );
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        logDO.setOperateTime(localDateTime.format(formatter));

        //设置操作人员ID
//        logDO.setAdminId(1);
//        Integer adminId = StpUtil.getLoginIdAsInt();
        logDO.setAdminId(StpUtil.getLoginIdAsInt());

        //调用service保存logDO实体类到数据库
        logService.addLog(logDO);
    }


}